﻿using System;
using System.Collections.Generic;
using System.Data;
using ContractManager.BLL.Business;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using ContractManager.Entity;

using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace ContractManager.Lists.Forms
{
    public partial class FrmFieldTableDetail : XtraFormBase
    {
        #region "Private Variable"
        
        public bool SaveClose;
        public bool SaveNew;
        public bool OnlyView;
        public int MasterId;

        
        #endregion

        #region "Form Construction"
        public FrmFieldTableDetail()
        {
            InitializeComponent();
        }
        #endregion

        #region "Private Method"

        private void BlankForm()
        {
            
            this.ResetControls();
            txtModuleName.EditValue = @"Quản lý nhân sự";
            txtTalbeGroupName.EditValue = @"Danh mục từ điển nhân sự";
            grdDetail.DataSource = ClsFieldTables.ListDetail(0);
          
        }

        private void GetSourceData()
        {
            var dt = ClsSourceData.SelectAll();
            txtSourceDataId.Properties.DataSource = dt;
            txtSourceDataId.Properties.ValueMember = "SourceDataId";
            txtSourceDataId.Properties.DisplayMember = "SourceDataName";

            repositoryItemSearchLookUpEdit1.DataSource = dt;
            repositoryItemSearchLookUpEdit1.ValueMember = "SourceDataId";
            repositoryItemSearchLookUpEdit1.DisplayMember = "SourceDataName";


            var form = ClsForms.SelectAll();
            txtFormNo.Properties.DataSource = form;
            txtFormNo.Properties.ValueMember = "FormNo";
            txtFormNo.Properties.DisplayMember = "Form_Name";

            txtDictionaryFormNo.Properties.DataSource = form;
            txtDictionaryFormNo.Properties.ValueMember = "FormNo";
            txtDictionaryFormNo.Properties.DisplayMember = "Form_Name";

            
        }


        private void GetDetail()
        {
            var detail = ClsFieldTables.SelectByPk(MasterId);
            if (detail != null)
            {
                txtFieldTableName.EditValue = String.Format("{0}", detail.FieldTableName);
                txtFieldTableDescription.EditValue = String.Format("{0}", detail.FieldTableDescription);
                txtFieldTalbeType.SelectedIndex = Convert.ToInt32(detail.FieldTalbeType)-1;
                txtSourceDataId.EditValue = detail.SourceDataId;

                txtDisplayMember.EditValue = String.Format("{0}", detail.DisplayMember);
                txtValueMember.EditValue = String.Format("{0}", detail.ValueMember);
                txtFieldHasEvents.Checked = Convert.ToBoolean(detail.FieldHasEvents);

                txtFieldTableFormula.EditValue = String.Format("{0}", detail.FieldTableFormula);
                txtParentValueMember.EditValue = String.Format("{0}", detail.ParentValueMember);

                txtGridLayoutName.EditValue = String.Format("{0}", detail.GridLayoutName);
                txtValidateExpress.EditValue = String.Format("{0}", detail.ValidateExpress);

                txtGridTable.EditValue = String.Format("{0}", detail.GridTable);
                txtGridTableKeyField.EditValue = String.Format("{0}", detail.GridTableKeyField);
                txtGridLayoutFieldWith.EditValue = String.Format("{0}", detail.GridLayoutFieldWith);

                txtFieldTableKeyField.EditValue = String.Format("{0}", detail.FieldTableKeyField);
                txtTableName.EditValue = String.Format("{0}", detail.TableName);


                chkReadOnly.EditValue = detail.FieldTableReadOnly;

                chkIsTabStop.EditValue = detail.FieldTableIsTabStop;
                txtFormNo.EditValue = detail.FormNo;

                chkIsValidate.EditValue = detail.FieldTalbeIsValidate;
                txtFieldTableValidateType.SelectedIndex = Convert.ToInt32(detail.FieldTableValidateType) - 1;

                txtFieldTableValidateFromNumber.EditValue = detail.FieldTableValidateFromNumber;
                txtFieldTableValidateToNumber.EditValue = detail.FieldTableValidateToNumber;

                txtFieldTableValidateFromDate.EditValue = String.Format("{0}", detail.FieldTableValidateFromDate);
                txtFieldTableValidateToDate.EditValue = String.Format("{0}", detail.FieldTableValidateToDate);

                txtFieldTableListLookupChange.EditValue = String.Format("{0}", detail.FieldTableListLookupChange);

                txtFieldTableListViewFieldReadOnly.EditValue = String.Format("{0}", detail.FieldTableListViewFieldReadOnly);

                txtModuleName.EditValue = String.Format("{0}", detail.ModuleName);
                txtTalbeGroupName.EditValue = String.Format("{0}", detail.TalbeGroupName);

                chkCheckDuplicate.EditValue = detail.FieldTableIsCheckDuplicate;

                chkAutoNumber.EditValue = detail.FieldTableIsAutoNumber;

                chkAddButton.EditValue = detail.FieldTableAddButton;

                txtDictionaryFormNo.EditValue = detail.FieldTableFormNo;

                txtFieldTableListWhereField.EditValue = String.Format("{0}", detail.FieldTableListWhereField);

                grdDetail.DataSource = ClsFieldTables.ListDetail(MasterId);

            }   
        }

        private void DoSave()
        {
            grdDetail.EmbeddedNavigator.Buttons.DoClick(grdDetail.EmbeddedNavigator.Buttons.EndEdit);

            #region "Variable"

            var dtSource = (DataTable)grdDetail.DataSource;

            #endregion

            #region "Check Condition"
            //if (!FormIsNotValidate)
            //{
            //    if (!dxValidationProvider.Validate())
            //    {
            //        XtraMessageBox.Show(
            //                    "Vui lòng nhập đầy đủ thông tin trước khi lưu",
            //                    "Thông báo",
            //                    MessageBoxButtons.OK,
            //                    MessageBoxIcon.Error);
            //        txtCode.SelectAll();
            //        txtCode.Focus();
            //        return;
            //    }
            //}
            #endregion

            FieldTables item = MasterId <= 0 ? new FieldTables() : ClsFieldTables.SelectByPk(MasterId);
            item.FieldTableId = MasterId;
            item.FieldTableName = String.Format("{0}", txtFieldTableName.EditValue);
            item.FieldTableDescription = String.Format("{0}", txtFieldTableDescription.EditValue);
            item.FieldTalbeType = Convert.ToInt32(txtFieldTalbeType.SelectedIndex+1);

            if (txtSourceDataId.EditValue != null) item.SourceDataId = Convert.ToInt32(txtSourceDataId.EditValue);
            item.DisplayMember = String.Format("{0}", txtDisplayMember.EditValue);
            item.ValueMember = String.Format("{0}", txtValueMember.EditValue);

            item.FieldHasEvents = txtFieldHasEvents.Checked;
            item.FieldTableFormula = String.Format("{0}", txtFieldTableFormula.EditValue);
            item.ParentValueMember = String.Format("{0}", txtParentValueMember.EditValue);

            item.GridLayoutName = String.Format("{0}", txtGridLayoutName.EditValue);
            item.ValidateExpress = String.Format("{0}", txtValidateExpress.EditValue);

            item.GridTable = String.Format("{0}", txtGridTable.EditValue);
            item.GridTableKeyField = String.Format("{0}", txtGridTableKeyField.EditValue);
            item.GridLayoutFieldWith = String.Format("{0}", txtGridLayoutFieldWith.EditValue);

            item.FieldTableKeyField = String.Format("{0}", txtFieldTableKeyField.EditValue);
            item.TableName = String.Format("{0}", txtTableName.EditValue);

            item.FieldTableReadOnly = chkReadOnly.Checked;
            item.FieldTableIsTabStop = chkIsTabStop.Checked;
            item.FormNo = Convert.ToInt32(txtFormNo.EditValue);

            item.FieldTalbeIsValidate = chkIsValidate.Checked;
            item.FieldTableValidateType = Convert.ToInt32(txtFieldTableValidateType.SelectedIndex)+1;

            item.FieldTableValidateFromNumber = Convert.ToDouble(txtFieldTableValidateFromNumber.Value);
            item.FieldTableValidateToNumber = Convert.ToDouble(txtFieldTableValidateToNumber.Value);

            item.FieldTableValidateFromDate = String.Format("{0}", txtFieldTableValidateFromDate.EditValue);
            item.FieldTableValidateToDate = String.Format("{0}", txtFieldTableValidateToDate.EditValue);
            item.FieldTableListLookupChange = String.Format("{0}", txtFieldTableListLookupChange.EditValue);

            item.FieldTableListViewFieldReadOnly = String.Format("{0}", txtFieldTableListViewFieldReadOnly.EditValue);

            item.ModuleName = String.Format("{0}", txtModuleName.EditValue);
            item.TalbeGroupName = String.Format("{0}", txtTalbeGroupName.EditValue);

            item.FieldTableIsCheckDuplicate = chkCheckDuplicate.Checked;
            item.FieldTableIsAutoNumber = chkAutoNumber.Checked;

            item.FieldTableAddButton = chkAddButton.Checked;

            if (txtDictionaryFormNo.EditValue != null)
                item.FieldTableFormNo = Convert.ToInt32(txtDictionaryFormNo.EditValue);

            item.FieldTableListWhereField = String.Format("{0}", txtFieldTableListWhereField.EditValue);

            item.ListAdd = GetListAdd(dtSource.GetChanges(DataRowState.Added));
            item.ListUpdate = GetListUpdate(dtSource.GetChanges(DataRowState.Modified));
            item.ListDelete = GetListDelete(dtSource.GetChanges(DataRowState.Deleted));

            try
            {
                if (MasterId > 0)
                {
                    ClsFieldTables.Update(item); 
                }
                else
                {

                    ClsFieldTables.Insert(item);
                    MasterId = item.FieldTableId;
                }
                if (SaveNew)
                {
                    MasterId = 0;
                    BlankForm();
                    txtFieldTableName.Focus();
                }
                else if (SaveClose)
                {
                    Close();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                    String.Format("Có lỗi xảy ra trong quá trình cập nhật dữ liệu. {0}", ex.Message),
                    "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void DoDelete()
        {
            if (MasterId <= 0) return;
            
            try
            {
                if (
                        XtraMessageBox.Show(
                                        "Bạn có muốn xóa bản ghi này không?",
                                        "Thông báo",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question) == DialogResult.No) return;
                ClsFieldTables.DeleteByPk(MasterId);
                Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                       "Có lỗi xảy ra trong quá trình xóa dữ liệu. " + ex.Message,
                       "Thông báo",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
            }
        }

        private List<FieldTableDetails> GetListAdd(DataTable dataTable)
        {
            List<FieldTableDetails> list = new List<FieldTableDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    FieldTableDetails item = new FieldTableDetails();
                    item.FieldTableDetailId = 0;
                    item.FieldTableId = 0;
                    item.FieldTableDetailColumnName = String.Format("{0}", row["FieldTableDetailColumnName"]);
                    item.FieldTableDetailGetValueFromColumn = String.Format("{0}", row["FieldTableDetailGetValueFromColumn"]);
                    item.FieldTableDetailHasEvent = row["FieldTableDetailHasEvent"] != DBNull.Value && Convert.ToBoolean(row["FieldTableDetailHasEvent"]);

                    item.FieldTableDetailFormula = String.Format("{0}", row["FieldTableDetailFormula"]);

                    item.FieldTableType = row["FieldTableType"] == DBNull.Value ? 0 : Convert.ToInt32(row["FieldTableType"]);
                    item.SourceDataId = row["SourceDataId"] == DBNull.Value ? 0 : Convert.ToInt32(row["SourceDataId"]);
                    item.DisplayMember = String.Format("{0}", row["DisplayMember"]);
                    item.ValueMember = String.Format("{0}", row["ValueMember"]);
                    item.FieldTableLayout = String.Format("{0}", row["FieldTableLayout"]);

                    item.FieldTableListField = String.Format("{0}", row["FieldTableListField"]);
                    item.FieldTableListCaption = String.Format("{0}", row["FieldTableListCaption"]);

                    item.FieldTableListWhereField = String.Format("{0}", row["FieldTableListWhereField"]);
                    item.SourceDataIdWhere = row["SourceDataIdWhere"] == DBNull.Value ? 0 : Convert.ToInt32(row["SourceDataIdWhere"]);
                    item.FieldTableGetWhereField = String.Format("{0}", row["FieldTableGetWhereField"]);

                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<FieldTableDetails> GetListUpdate(DataTable dataTable)
        {
            List<FieldTableDetails> list = new List<FieldTableDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    FieldTableDetails item = new FieldTableDetails();
                    item.FieldTableDetailId = Convert.ToInt32(row["FieldTableDetailId"]);
                    item.FieldTableId = 0;
                    item.FieldTableDetailColumnName = String.Format("{0}", row["FieldTableDetailColumnName"]);
                    item.FieldTableDetailGetValueFromColumn = String.Format("{0}", row["FieldTableDetailGetValueFromColumn"]);
                    item.FieldTableDetailHasEvent = row["FieldTableDetailHasEvent"] != DBNull.Value && Convert.ToBoolean(row["FieldTableDetailHasEvent"]);

                    item.FieldTableDetailFormula = String.Format("{0}", row["FieldTableDetailFormula"]);

                    item.FieldTableType = row["FieldTableType"] == DBNull.Value ? 0 : Convert.ToInt32(row["FieldTableType"]);
                    item.SourceDataId = row["SourceDataId"] == DBNull.Value ? 0 : Convert.ToInt32(row["SourceDataId"]);
                    item.DisplayMember = String.Format("{0}", row["DisplayMember"]);
                    item.ValueMember = String.Format("{0}", row["ValueMember"]);
                    item.FieldTableLayout = String.Format("{0}", row["FieldTableLayout"]);

                    item.FieldTableListField = String.Format("{0}", row["FieldTableListField"]);
                    item.FieldTableListCaption = String.Format("{0}", row["FieldTableListCaption"]);

                    item.FieldTableListWhereField = String.Format("{0}", row["FieldTableListWhereField"]);
                    item.SourceDataIdWhere = row["SourceDataIdWhere"] == DBNull.Value ? 0 : Convert.ToInt32(row["SourceDataIdWhere"]);
                    item.FieldTableGetWhereField = String.Format("{0}", row["FieldTableGetWhereField"]);

                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<FieldTableDetails> GetListDelete(DataTable dataTable)
        {
            List<FieldTableDetails> list = new List<FieldTableDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    FieldTableDetails item = new FieldTableDetails();
                    item.FieldTableDetailId = Convert.ToInt32(row["FieldTableDetailId", DataRowVersion.Original]);
                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        #endregion

        #region "Form Event"
        private void FrmFieldTableDetailLoad(object sender, EventArgs e)
        {
            GetSourceData();
            BlankForm();
            if (!String.IsNullOrEmpty(FormXtraLayoutTemplate))
            {
                var fileLayout = ClsVariable.GetRestoreLayoutFullPath(FormXtraLayoutTemplate);
                layoutControl.RestoreLayoutFromXml(fileLayout);
            }
            if (MasterId > 0) GetDetail();
            btnSaveNew.Enabled = !OnlyView;
            btnSave.Enabled = !OnlyView;
            btnSaveClose.Enabled = !OnlyView;
            btnDelete.Enabled = !OnlyView;
            btnDesign.Enabled = !OnlyView;
           
        }
        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnSave":
                    DoSave();
                    break;
                case "btnSaveNew"://Lưu và thêm mới
                    SaveNew = true;
                    SaveClose = false;
                    DoSave();
                    break;
                case "btnSaveClose"://Lưu và đóng
                    SaveClose = true;
                    SaveNew = false;
                    DoSave();
                    break;
                case "btnDelete":
                    DoDelete();
                    break;
                case "btnDesign":
                    break;
                case "btnRefresh"://Nạp lại danh mục
                    break;
                case "btnHistory"://History
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }
        #endregion
    }
}
